/**
 * Excel 查看器
 * 
 * 功能：
 * - 支持拖拽上传 Excel 文件
 * - 解析并展示 Excel 数据
 * - 支持 .xls, .xlsx, .csv 格式
 */

import { useState, useRef, useMemo } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { 
  Upload, 
  FileSpreadsheet, 
  Loader2, 
  AlertCircle,
  Download,
  RefreshCw,
  X
} from 'lucide-react';

// 定义数据接口
interface ExcelData {
  columns: string[];
  rows: Record<string, any>[];
  stats: {
    rows: number;
    columns: number;
    filename: string;
  };
}

interface ApiResponse {
  success: boolean;
  data?: ExcelData;
  message?: string;
  error?: string;
}

/**
 * Excel 查看器组件
 */
export default function ExcelViewer() {
  // ==================== 状态管理 ====================
  const [excelData, setExcelData] = useState<ExcelData | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [dragActive, setDragActive] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [search, setSearch] = useState('');
  const API_BASE = (import.meta as any).env?.VITE_API_BASE_URL || 'http://localhost:5001/api';

  // ==================== 文件上传 ====================
  const uploadFile = async (file: File) => {
    try {
      setLoading(true);
      setError(null);

      // 检查文件类型
      const validTypes = ['application/vnd.ms-excel', 
                          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                          'text/csv'];
      const validExtensions = ['.xls', '.xlsx', '.csv'];
      const hasValidExtension = validExtensions.some(ext => file.name.toLowerCase().endsWith(ext));
      
      if (!validTypes.includes(file.type) && !hasValidExtension) {
        throw new Error('只支持 .xls, .xlsx, .csv 格式的文件');
      }

      // 创建 FormData
      const formData = new FormData();
      formData.append('file', file);

      // 发送请求
      const token = localStorage.getItem('access_token');
      const response = await fetch(`${API_BASE}/excel-viewer/upload`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
        body: formData,
      });

      const data: ApiResponse = await response.json();

      if (data.success && data.data) {
        setExcelData(data.data);
        setError(null);
      } else {
        throw new Error(data.error || '上传失败');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : '上传失败');
      console.error('Failed to upload file:', err);
    } finally {
      setLoading(false);
    }
  };

  // ==================== 拖拽处理 ====================
  const handleDrag = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === 'dragenter' || e.type === 'dragover') {
      setDragActive(true);
    } else if (e.type === 'dragleave') {
      setDragActive(false);
    }
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);

    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      uploadFile(e.dataTransfer.files[0]);
    }
  };

  // ==================== 文件选择 ====================
  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      uploadFile(e.target.files[0]);
    }
  };

  const handleButtonClick = () => {
    fileInputRef.current?.click();
  };

  // ==================== 清除数据 ====================
  const handleClear = () => {
    setExcelData(null);
    setError(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  // 基于关键字的简单筛选
  const filteredRows = useMemo(() => {
    if (!excelData) return [] as Record<string, any>[];
    if (!search.trim()) return excelData.rows;
    const q = search.toLowerCase();
    return excelData.rows.filter((row) =>
      excelData.columns.some((col) => String(row[col] ?? '').toLowerCase().includes(q))
    );
  }, [excelData, search]);

  // ==================== 导出数据 ====================
  const handleExport = () => {
    if (!excelData) return;

    // 创建 CSV 内容
    const csvContent = [
      excelData.columns.join(','),
      ...excelData.rows.map(row => 
        excelData.columns.map(col => {
          const value = row[col];
          // 如果值包含逗号或引号，需要用引号包裹
          if (typeof value === 'string' && (value.includes(',') || value.includes('"'))) {
            return `"${value.replace(/"/g, '""')}"`;
          }
          return value;
        }).join(',')
      )
    ].join('\n');

    // 创建下载链接
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `${excelData.stats.filename.split('.')[0]}_exported.csv`;
    link.click();
  };

  // ==================== 渲染逻辑 ====================

  return (
    <div className="space-y-6">
      {/* ========== 页面标题 ========== */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">Excel 查看器</h1>
          <p className="text-muted-foreground mt-2">
            上传并查看 Excel 文件内容（支持 .xls, .xlsx, .csv）
          </p>
        </div>
        
        {excelData && (
          <div className="flex gap-2">
            <Button onClick={handleExport} variant="outline" size="sm">
              <Download className="h-4 w-4 mr-2" />
              导出 CSV
            </Button>
            <Button onClick={handleClear} variant="outline" size="sm">
              <RefreshCw className="h-4 w-4 mr-2" />
              重新上传
            </Button>
          </div>
        )}
      </div>

      {/* ========== 错误提示 ========== */}
      {error && (
        <div className="flex items-center gap-2 p-4 bg-destructive/10 border border-destructive rounded-lg">
          <AlertCircle className="h-5 w-5 text-destructive" />
          <p className="text-destructive">{error}</p>
          <Button 
            onClick={() => setError(null)} 
            variant="ghost" 
            size="sm"
            className="ml-auto"
          >
            <X className="h-4 w-4" />
          </Button>
        </div>
      )}

      {/* ========== 上传区域 ========== */}
      {!excelData && (
        <Card>
          <CardContent className="pt-6">
            <div
              onDragEnter={handleDrag}
              onDragLeave={handleDrag}
              onDragOver={handleDrag}
              onDrop={handleDrop}
              className={`
                border-2 border-dashed rounded-lg p-12 text-center transition-colors
                ${dragActive ? 'border-primary bg-primary/5' : 'border-muted'}
                ${loading ? 'opacity-50 pointer-events-none' : 'cursor-pointer hover:border-primary/50'}
              `}
              onClick={!loading ? handleButtonClick : undefined}
            >
              <input
                ref={fileInputRef}
                type="file"
                accept=".xls,.xlsx,.csv"
                onChange={handleFileSelect}
                className="hidden"
                disabled={loading}
              />
              
              {loading ? (
                <div className="flex flex-col items-center gap-4">
                  <Loader2 className="h-12 w-12 animate-spin text-primary" />
                  <p className="text-lg font-medium">正在解析文件...</p>
                </div>
              ) : (
                <div className="flex flex-col items-center gap-4">
                  <div className="p-4 bg-primary/10 rounded-full">
                    <Upload className="h-8 w-8 text-primary" />
                  </div>
                  <div>
                    <p className="text-lg font-medium">
                      拖拽文件到此处，或点击上传
                    </p>
                    <p className="text-sm text-muted-foreground mt-2">
                      支持 .xls, .xlsx, .csv 格式
                    </p>
                  </div>
                  <Button variant="outline" size="sm">
                    <FileSpreadsheet className="h-4 w-4 mr-2" />
                    选择文件
                  </Button>
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      )}

      {/* ========== 统计信息 ========== */}
      {excelData && (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">
                文件名
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="flex items-center gap-2">
                <FileSpreadsheet className="h-5 w-5 text-primary" />
                <p className="text-lg font-semibold truncate">
                  {excelData.stats.filename}
                </p>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">
                总行数
              </CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-2xl font-bold">{excelData.stats.rows}</p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">
                总列数
              </CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-2xl font-bold">{excelData.stats.columns}</p>
            </CardContent>
          </Card>
        </div>
      )}

      {/* ========== 数据表格 ========== */}
      {excelData && (
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between gap-3">
              <CardTitle>数据预览</CardTitle>
              <input
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder="输入关键字筛选..."
                className="h-9 w-64 rounded-md border bg-background px-3 text-sm"
              />
            </div>
          </CardHeader>
          <CardContent>
            <div className="overflow-x-auto">
              <table className="w-full border-collapse">
                <thead>
                  <tr className="border-b bg-muted/50">
                    <th className="px-4 py-3 text-left text-sm font-medium text-muted-foreground">
                      #
                    </th>
                    {excelData.columns.map((column, index) => (
                      <th 
                        key={index}
                        className="px-4 py-3 text-left text-sm font-medium"
                      >
                        <div className="flex items-center gap-2">
                          <span>{column}</span>
                          <Badge variant="secondary" className="text-xs">
                            {index + 1}
                          </Badge>
                        </div>
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {filteredRows.map((row, rowIndex) => (
                    <tr 
                      key={rowIndex}
                      className="border-b hover:bg-muted/50 transition-colors"
                    >
                      <td className="px-4 py-3 text-sm text-muted-foreground">
                        {rowIndex + 1}
                      </td>
                      {excelData.columns.map((column, colIndex) => (
                        <td 
                          key={colIndex}
                          className="px-4 py-3 text-sm"
                        >
                          {row[column] !== undefined && row[column] !== null 
                            ? String(row[column]) 
                            : '-'}
                        </td>
                      ))}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {filteredRows.length === 0 && (
              <div className="text-center py-12 text-muted-foreground">
                <p>没有匹配的数据</p>
              </div>
            )}
          </CardContent>
        </Card>
      )}
    </div>
  );
}

